// src/components/renderer.tsx
import React, {useEffect, useRef, useState} from 'react';
import Quill from "quill";

interface Props {
    value: string
}

// 渲染quill消息(富文本)内容
const Renderer = ({value}: Props) => {
    const [isEmpty, setIsEmpty] = useState(false);
    const rendererRef = useRef<HTMLDivElement>(null)

    useEffect(() => {
        // console.log(value)
        if (!rendererRef.current) return

        const container = rendererRef.current

        const quill = new Quill(document.createElement('div'), {
            theme: 'snow'
        })

        quill.enable(false)

        const contents = JSON.parse(value)
        quill.setContents(contents)

        const isEmpty = quill.getText()
            .replace(/<(.|\n)*?>/g, '').trim().length === 0
        setIsEmpty(isEmpty)

        container.innerHTML = quill.root.innerHTML

        return () => {
            if (container) {
                container.innerHTML = ''
            }
        }
    }, [value]);

    if (isEmpty) return null

    return (
        <div ref={rendererRef} className={`ql-editor ql-renderer`}/>
    );
};

export default Renderer;